package per.dj.testpro.entity.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;
import per.dj.testpro.utils.common.Tools;

@Data
public class MessageHeader {

    /**
     * 消息长度
     */
    private int messageSize;

    public int getMessageSize() {
        return messageSize;
    }

    public void setMessageSize(int messageSize) {
        this.messageSize = messageSize;
    }

    /**
     * 设备编号
     */
    private String simId;

    /**
     * 消息id
     */
    private int messageId;


    /**
     * 消息流水号
     */
    private Byte messageSerialNo;



    public final byte[] WriteToBytes() {

        ByteBuf buff = Unpooled.buffer(12);
        try{
            buff.writeShort((short) getMessageSize());
            byte[] simIdBytes = Tools.HexString2Bytes(simId);
            buff.writeBytes(simIdBytes);
            buff.writeByte(getMessageId());
            buff.writeByte(getMessageSerialNo());

            return buff.array();
        }finally {
            if(buff != null){
                buff.release();
            }
        }

    }

    public final void ReadFromBytes(byte[] headerBytes) {
        ByteBuf buff = Unpooled.buffer(headerBytes.length);
        buff.writeBytes(headerBytes);
        setMessageSize(buff.readShort());
        setSimId(String.format("%02X", buff.readByte())
                + String.format("%02X", buff.readByte())
                + String.format("%02X", buff.readByte())
                + String.format("%02X", buff.readByte())
                + String.format("%02X", buff.readByte())
                + String.format("%02X", buff.readByte())
                + String.format("%02X", buff.readByte())
                + String.format("%02X", buff.readByte()));
        setMessageId(buff.readByte());
        setMessageSerialNo(buff.readByte());
    }

}